﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using WooCoo.Reflection;

namespace WooCoo.DataPortal.Server
{
    /// <summary>
    /// 业务对象到服务端后对应的服务对象工作
    /// </summary>
    public sealed class ServiceBoundFactory
    {
        public readonly static ServiceBoundFactory Instance = new ServiceBoundFactory();

        private ServiceBoundFactory()
        {
            LoadConfig();
        }

        private Dictionary<string, Type> _config = new Dictionary<string, Type>();

        /// <summary>
        /// 将配置的类加入到缓存中.该方法为外部方法调用.
        /// </summary>
        /// <param name="bizType"></param>
        /// <param name="SvrType"></param>
        public void AddConfig(string inType, string SvrType)
        {
            //var svrO = System.Activator.CreateInstance(Type.GetType(SvrType, true, true)) as IDataPortalBehavior;
            _config.Add(inType, Type.GetType(SvrType, true, true));
        }

        public Type GetServiceType(string inType)
        {
            if (_config.ContainsKey(inType))
                return _config[inType];
            throw new NotImplementedException(StringID.NoFoundSvrType.ToLocalStringFormat(inType));
        }

        public object GetServiceObject(string inType)
        {
            return MethodCaller.CreateInstance(GetServiceType(inType));
        }

        private void LoadConfig()
        {
            string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Config\ServiceBound.xml");
            if (!System.IO.File.Exists(filePath))
            {
                //throw new System.IO.FileNotFoundException("程序文件缺失:LookUp.Config配置文件不存在!");
                return;
            }
            //解释配置文件
            XElement appServer = XElement.Load(filePath);
            var configQuery = from configs in appServer.Elements("Bound")
                              select configs;
            foreach (XElement ele in configQuery)
            {
                if (ele.Attribute("InType") == null || ele.Attribute("ServiceType") == null)
                    continue;
                var bt = ele.Attribute("InType").Value;
                var st = ele.Attribute("ServiceType").Value;
                AddConfig(bt, st);
            }

        }
    }
}
